<!--  线 + 柱混合图 -->
<template>
  <el-card>
    <template #header>
      <div class="title">
        <div class="chart-title" @click="showBlur = !showBlur">
          {{ chartTitle }}
        </div>
        <div v-if="!showBlur">
          <el-tooltip
            effect="dark"
            content="上级数据"
            placement="bottom"
            v-if="parentDataId != 0"
          >
            <i-ep-back class="download" @click="showParentData" />
          </el-tooltip>
          <el-tooltip effect="dark" content="点击试试下载" placement="bottom">
            <i-ep-download class="download" @click="downloadEchart" />
          </el-tooltip>
        </div>
      </div>
    </template>

    <div :id="id" :class="className" :style="{ height, width }"></div>
    <div
      class="zhezhaox"
      :style="{ height: height, 'margin-top': '-' + height }"
      v-if="showBlur"
    >
      <div class="zhezhaox2" @click="showBlur = !showBlur"></div>
    </div>
  </el-card>
  <BillRecordDialog ref="listDialog" />
</template>

<script setup lang="ts">
const showBlur = ref<boolean>(true);
import { onMounted, defineProps } from "vue";
import * as echarts from "echarts";
// import { getBillEntityPage } from "@/api/billEntity";
import { formatPrice } from "@/utils/format";
// import { BillEntityPageQuery, BillEntityPageVO } from "@/api/billEntity/types";

import { listBillEntities } from "@/api/billEntity";

import { BillEntityQuery, BillEntityVO } from "@/api/billEntity/types";
import { BillRecordQuery } from "@/api/billRecord/types";

const props = defineProps({
  id: {
    type: String,
    default: "barChart",
  },
  className: {
    type: String,
    default: "",
  },
  width: {
    type: String,
    default: "200px",
    required: true,
  },
  height: {
    type: String,
    default: "200px",
    required: true,
  },
  bindTag: {
    type: String,
  },
  types: {
    type: String,
  },
  chartTitle: {
    type: String,
    required: true,
  },
  isSort: {
    type: Boolean,
    required: true,
    default: false,
  },
  dataType: {
    type: String,
    required: true,
    default: "difference",
  },
});

const options = {
  dataset: [
    {
      dimensions: ["name", "from", "to", "difference"] as String[],
      source: [] as any,
    },
    {
      transform: {
        type: "sort",
        config: { dimension: props.dataType, order: "desc" },
      },
    },
  ],
  grid: {
    left: "2%",
    right: "2%",
    bottom: "10%",
    containLabel: true,
  },
  tooltip: {
    trigger: "axis",
    axisPointer: {
      type: "cross",
      crossStyle: {
        color: "#999",
      },
    },
    valueFormatter: function (value: any) {
      return formatPrice(value);
    },
  },
  xAxis: {
    type: "category",
    axisPointer: {
      type: "shadow",
    },
    axisLabel: {
      interval: 0,
      rotate: 45,
    },
  },
  yAxis: {
    type: "value",
    axisLabel: {
      formatter: function (value: number, index: number) {
        return formatPrice(value);
      },
    },
  },
  series: {
    type: "bar",
    encode: { x: "name", y: props.dataType },
    datasetIndex: 1,
    itemStyle: {},
    label: {
      show: true,
      fontSize: 10,
      position: "top",
      formatter: function (params: any, index: number) {
        let value = params.value[params.encode.y[0]];
        return formatPrice(value);
      },
    },
  },
};

// const queryParams = reactive<BillEntityPageQuery>({
//   pageNum: 1,
//   pageSize: -1,
//   types: props.types?.split(","),
// });

const queryParams = reactive<BillEntityQuery>({
  types: props.types?.split(","),
});

let entities: BillEntityVO[] = [];
let entityIdMap: any = {};
let entityNameToId: any = {};

function setEntityIdMap(entityList?: BillEntityVO[]) {
  if (entityList != undefined) {
    entityList.forEach((entity) => {
      entityIdMap[entity.id] = entity;
      entityNameToId[entity.name] = entity.id;
      setEntityIdMap(entity.children);
    });
  }
}

function showParentData() {
  let nowParentEntity: BillEntityVO = entityIdMap[parentDataId.value];
  if (nowParentEntity == undefined) {
    setChartByParentId(0);
  } else {
    setChartByParentId(nowParentEntity.parentId ? nowParentEntity.parentId : 0);
  }
}

const parentDataId = ref<number>(0);
function setChartByParentId(parentId: number) {
  // chart.value.clear();
  // chart.value.setOption(options);
  let optionsParams = {
    dataset: {
      source: [] as any,
    },
  };

  let nowParentEntity: BillEntityVO = entityIdMap[parentId];
  let nowEntities: BillEntityVO[] = [];
  if (nowParentEntity == undefined) {
    nowEntities = entities;
    parentDataId.value = 0;
  } else {
    nowEntities = nowParentEntity.children;
    parentDataId.value = nowParentEntity.id;
  }

  nowEntities.forEach((entity) => {
    const tags: string[] = entity.tagNames ? entity.tagNames.split(",") : [];
    if (!props.bindTag || tags.includes(props.bindTag)) {
      const name: string = entity.name ? entity.name : "";
      const fromNum: number = entity.allFromNum ? entity.allFromNum : 0;
      const toNum: number = entity.allToNum ? entity.allToNum : 0;
      const differenceNum: number = toNum - fromNum;
      optionsParams.dataset.source.push([name, fromNum, toNum, differenceNum]);
    }
  });
  chart.value.setOption(optionsParams);
}

/** 查询 */
async function handleQuery() {
  // return getBillEntityPage(queryParams)
  //   .then(({ data }) => {
  //     console.log(data)
  //     options.dataset[0].source.length = 0;
  //     for (let index = 0; index < data.list.length; index++) {
  //       const element: BillEntityPageVO = data.list[index];
  //       const tags: string[] = element.tagNames
  //         ? element.tagNames.split(",")
  //         : [];
  //       if (!props.bindTag || tags.includes(props.bindTag)) {
  //         const name: string = element.name
  //           ? element.name /* + "(" + element.id + ")" */
  //           : "";
  //         const fromNum: number = element.fromNum ? element.fromNum : 0;
  //         const toNum: number = element.toNum ? element.toNum : 0;
  //         const differenceNum: number = toNum - fromNum;
  //         options.dataset[0].source.push([name, fromNum, toNum, differenceNum]);
  //       }
  //     }
  //   })
  //   .finally(() => {});

  return listBillEntities(queryParams)
    .then(({ data }) => {
      console.log(data);
      entities = data;
      entityIdMap = {};
      setEntityIdMap(entities);
      setChartByParentId(0);
    })
    .finally(() => {});
}

const chart = ref<any>("");
async function createChart() {
  // 图表初始化
  chart.value = markRaw(
    echarts.init(document.getElementById(props.id) as HTMLDivElement)
  );

  if (props.dataType == "to") {
    options.series.itemStyle = {
      color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: "#83bff6" },
        { offset: 0.5, color: "#188df0" },
        { offset: 1, color: "#188df0" },
      ]),
    };
  } else if (props.dataType == "from") {
    options.series.itemStyle = {
      color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: "#25d73c" },
        { offset: 0.5, color: "#1bc23d" },
        { offset: 1, color: "#179e61" },
      ]),
    };
  } else {
    // console.log(options)
    options.series.itemStyle = {
      color: function (params: any) {
        //根据数值大小设置相关颜色
        if (params.value[params.encode.y[0]] > 0) {
          return "green";
        } else {
          return "red";
        }
      },
    };
  }
  chart.value.setOption(options);

  await handleQuery();
  chart.value.on("click", function (event: any) {
    if (event.data) {
      console.log(event.data[0]);
      let id = entityNameToId[event.data[0]];
      // if (id && entityIdMap[id].children.length > 0) {
      //   setChartByParentId(id);
      // }
      if (id) {
        if (entityIdMap[id].children.length > 0) {
          setChartByParentId(id);
        } else {
          openDialog(id);
        }
      }
    }
  });

  // 大小自适应
  window.addEventListener("resize", () => {
    chart.value.resize();
  });
}

onMounted(() => {
  createChart();
});
const downloadEchart = () => {
  // 获取画布图表地址信息
  const img = new Image();
  img.src = chart.value.getDataURL({
    type: "png",
    pixelRatio: 1,
    backgroundColor: "#fff",
  });
  // 当图片加载完成后，生成 URL 并下载
  img.onload = () => {
    const canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;
    const ctx = canvas.getContext("2d");
    if (ctx) {
      ctx.drawImage(img, 0, 0, img.width, img.height);
      const link = document.createElement("a");
      link.download = props.chartTitle + `.png`;
      link.href = canvas.toDataURL("image/png", 0.9);
      document.body.appendChild(link);
      link.click();
      link.remove();
    }
  };
};

/**
 * 打开弹窗
 *
 */
const listDialog = ref();
function openDialog(id: number) {
  const params: BillRecordQuery = reactive<BillRecordQuery>({
    pageNum: 1,
    pageSize: 10,
  });

  if (props.dataType == "from") {
    params.fromEntityId = id;
  } else if (props.dataType == "to") {
    params.toEntityId = id;
  } else {
    params.fromOrToEntityId = id;
  }

  listDialog.value.openDialog(params);
}
</script>
<style lang="scss" scoped>
.title {
  display: flex;
  justify-content: space-between;

  .download {
    cursor: pointer;

    &:hover {
      color: #409eff;
    }
  }
}

.zhezhaox {
  position: relative;
  width: 100%;

  .zhezhaox2 {
    position: absolute;
    inset: 0;
    background: rgb(255 255 255 / 5%);
    backdrop-filter: blur(5px);
    // z-index: 1000;
  }
}
</style>
